package bear;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class GetPic
{
	public GetPic()
	{
	}

	public static boolean saveUrlAs(String fileUrl, String savePath)/*
																	 * fileUrl
																	 * network
																	 * resources
																	 * address
																	 */
	{

		try
		{
			URL url = new URL(fileUrl);/*
										 * address of the network resources to
										 * pass, that url is assigned to
										 */
			/*
			 * This is the contact network resources usage of fixed format, so
			 * that later in variable input stream url interception network
			 * resources
			 */
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			DataInputStream in = new DataInputStream(connection.getInputStream());
			/*
			 * Here can also be used BufferedInputStream and
			 * BufferedOutputStream
			 */
			DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
			/*
			 * Parameter savepath, upcoming taken pictures stored in the local
			 * address assigned to the address specified by the out output
			 * stream
			 */
			byte[] buffer = new byte[4096];
			int count = 0;
			while ((count = in.read(buffer)) > 0)/*
												 * the input stream in the form
												 * of bytes read and write
												 * buffer
												 */
			{
				out.write(buffer, 0, count);
			}
			out.close();/*
						 * The next three acts Close input and output streams,
						 * and network resources fixed format
						 */
			in.close();
			connection.disconnect();
			return true;/*
						 * network resources interception and storage local to
						 * the successful return true
						 */

		}
		catch (Exception e)
		{
			System.out.println(e + fileUrl + savePath);
			return false;
		}
	}

	public static void main(String[] args)
	{
		GetPic pic = new GetPic();/* create instances */
		String photoUrl = "http://www.diegomarcheselli.com/images/dariociccone.jpg";
		/*
		 * PhotoUrl.substring (photoUrl.lastIndexOf ("/")the method returns the
		 * last symbol'/'Character after photoUrl variable wrapped this symbol
		 */
		String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
		String filePath = "C:/data/";
		/* Call the function and pass parameters */
		boolean flag = pic.saveUrlAs(photoUrl, filePath + fileName);
		System.out.println("Run ok!N Get URL file" + flag);
		System.out.println(filePath);
		System.out.println(fileName);
	}
}